import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../data/Data.dart';
import '../provider/AdbCurrentChangeProvider.dart';
import '../utils/CmdUtils.dart';

class AppProgressManager extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _AppProgressManager();
}

class _AppProgressManager extends State<AppProgressManager> {
  List<ProcessAppInfo> _appInfo = [];
  bool _isFilterSystem = true;
  AdbCurrentChangeProvider? provider;
  bool _isInit = false;
  bool _mounted = false;


  @override
  void initState() {
    super.initState();
    _mounted = true;
    if (!_isInit) {
      _isInit = true;
      init();
    }
  }


  @override
  void dispose() {
    _mounted = false;
    super.dispose();
  }

  void init() {
    _appInfo.clear();
    String line = "";
    CmdUtils.deviceProcess((success, error, process, successListener) {
      List<String> lineArray = success.trim().split("\r\n");
      if (success != "DONE") {
        for (String item in lineArray) {
          if (item.startsWith("USER")) {
            continue;
          }
          List<String> contentArray = item.trim().split(RegExp('\\s+'));
          /*if (contentArray.length != 9) {
            line = line + item;
            contentArray = line.trim().split(RegExp('\\s+'));
            if (contentArray.length != 9) {
              continue;
            }
          }*/
          line = "";
          debugPrint("输出内容：${item},分割长度为：${contentArray.length}");
          try {
            setState(() {
              if(!_mounted){
                return;
              }
              debugPrint("长度为：${_appInfo.length}");
              _appInfo.add(ProcessAppInfo(
                  contentArray[0],
                  contentArray[1],
                  contentArray[2],
                  contentArray[3],
                  contentArray[4],
                  contentArray[5],
                  contentArray[6],
                  contentArray[7],
                  contentArray[8]));
            });
          } catch (e) {
            debugPrint("长度为：${e}");
          }
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if (provider == null) {
      provider = Provider.of<AdbCurrentChangeProvider>(context);
      debugPrint("注册监听");
      provider?.addListener(() {
        init();
      });
    }
    return Container(
      alignment: Alignment.topLeft,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
              child: ListView.builder(
            itemCount: _appInfo.length,
            itemBuilder: (context, index) {
              return SizedBox(
                width: MediaQuery.of(context).size.width,
                height: 40,
                child: Row(
                  children: [
                    Expanded(
                      flex: 8,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.fromLTRB(10, 0, 0, 0),
                            child: Row(children: [
                              const Text(
                                textAlign: TextAlign.left,
                                "名称：",
                                style: TextStyle(fontSize: 12,fontWeight: FontWeight.bold),
                              ),
                              Text(
                                textAlign: TextAlign.left,
                                _appInfo[index].name,
                                style: const TextStyle(fontSize: 12),
                              )
                            ],),
                          ),
                          Padding(
                            padding: const EdgeInsets.fromLTRB(10, 0, 0, 0),
                            child: Row(
                              children: [
                                const Text("PID：",style: TextStyle(fontSize: 10,fontWeight: FontWeight.bold),),
                                Text(_appInfo[index].pid,style: const TextStyle(fontSize: 10)),
                                Padding(padding: const EdgeInsets.fromLTRB(10, 3, 0, 0),child:Row(children: [
                                  const Text("USER：",style: TextStyle(fontSize: 10,fontWeight: FontWeight.bold),),
                                  Text(_appInfo[index].user,style: const TextStyle(fontSize: 10))
                                ],),),
                                Padding(padding: const EdgeInsets.fromLTRB(10, 3, 0, 0),child:Row(children: [
                                  const Text("WCHAN：",style: TextStyle(fontSize: 10,fontWeight: FontWeight.bold),),
                                  Text(_appInfo[index].wchan,style: const TextStyle(fontSize: 10))
                                ],),)
                              ],
                            ),
                          )
                        ],
                      ),
                    ),
                    TextButton(
                      child: const Text(
                        "停止",
                        style: TextStyle(fontSize: 15),
                      ),
                      onPressed: () => {
                        CmdUtils.killProcess(_appInfo[index].pid),
                        setState(() {
                          if(!_mounted){
                            return;
                          }
                          _appInfo.removeAt(index);
                        })
                      },
                    ),
                  ],
                ),
              );
            },
          ))
        ],
      ),
    );
  }
}
